<?php
/**
 * 心愿支持模型类
 */

class CfSupportModel extends Model
{
    private $cf_support_id;



    /**
     * 构造函数
     * @author 姜伟
     * @todo 构造函数
     */
    public function __construct($cf_support_id=0)
    {
        parent::__construct();
        $this->cf_support_id = $cf_support_id;
    }  



    //获取心愿支持人数
    public function getCfSupportUserNum($cf_id){
        return $this->where('crowdfunding_id ='.$cf_id)->group('user_id')->count();
    }


    //获取支持者列表，根据支持的总金额倒序
    public function getCfSupportUserByMoney($cf_id){
        $r = $this->field('user_id, sum(support_money) as total_support_money, addtime')->where('crowdfunding_id ='.$cf_id)->group('user_id')->order('total_support_money desc')->select();
        foreach ($r as $k => $v) {
            $user = M('Users')->where('user_id ='.$v['user_id'])->find();
            $r[$k]['nickname'] = $user['nickname'];
            $r[$k]['headimgurl'] = $user['headimgurl'];
            $r[$k]['addtime'] = date('Y.m.d H:i:s', $v['addtime']);
        }

        return $r;
    }

    //查询心愿支持表的某个字段
    public function getSupportField($where,$field){
        return $this->where($where)->getField($field);
    }

    public function getSupportFields($where,$field,$group=''){
        return $this->where($where)->group($group)->getField($field,true);
    }


    public function getUserSupportNum($user_id, $cf_id){
        return $this->where('user_id ='.$user_id .' and crowdfunding_id ='.$cf_id)->count();
    }

    //修改退款字段
    public function setRefund($cf_support_id){
        return $this->where('cf_support_id ='.$cf_support_id)->save(array('is_refund' => 1 ));
    }

    public function getCfSupportNum($where = ''){
        return $this->where($where)->count();
    }

    //获取所有该心愿支持过的用户．
    public function getCfSupportAllList($cf_id){
        return $this->where('crowdfunding_id ='.$cf_id)->limit(1000000)->select();
    }

    public function addCfSupport($arr){
        if(!is_array($arr)) return false;
        $arr['addtime'] = time();
        $r = $this->add($arr);

        if($r){
            D('Crowdfunding')->support($arr['crowdfunding_id'], $arr['support_money']);
        }

        return $r;
    }

    public function getCfSupportList($field =null,$where, $order='addtime desc'){

        return $this->field($field)->where($where)->order($order)->limit()->select();
    }

    public function getListData($support_list){

        foreach ($support_list as $k => $v) {
            $user_obj = new UserModel();
            $support_list[$k]['nick_name'] = $user_obj ->getUserField('nickname','user_id ='.$v['user_id']);

            $support_list[$k]['add_time'] =date('Y-m-d H:i:s',$v['addtime']);
        }
        return $support_list;
    }


}
